package com.tjetc.service.impl;

import com.tjetc.constant.CodeConstant;
import com.tjetc.constant.RedisConstant;
import com.tjetc.constant.ShiMingCheckEnum;
import com.tjetc.domain.Patient;
import com.tjetc.util.Db;
import com.tjetc.util.IdCardCheckUtil;
import com.tjetc.util.JwtUtils;
import com.tjetc.util.SendMessageUtil;
import com.tjetc.vo.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.tjetc.domain.User;
import com.tjetc.mapper.UserMapper;
import com.tjetc.service.UserService;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;

import static com.tjetc.constant.CodeConstant.UNREGISTERED;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(User record) {
        return userMapper.insert(record);
    }

    @Override
    public int insertSelective(User record) {
        return userMapper.insertSelective(record);
    }

    @Override
    public User selectByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(User record) {
        return userMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(User record) {
        return userMapper.updateByPrimaryKey(record);
    }

    @Override
    public Result login(String phone) {
        User user = userMapper.selectByPhone(phone);
        if (user == null) {
            return new Result().setCode(CodeConstant.UNREGISTERED);
        }
        System.out.println(phone);
        String code = null;
        try {
            code = SendMessageUtil.sendMessage(phone);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("服务器内部错误,发送短信失败");
        }
        if (code == null) {
            return Result.fail("服务器内部错误,发送短信失败");
        }
        Db.jedis.set(RedisConstant.LOGIN_CODE_KEY + phone, code);
        Db.jedis.expire(RedisConstant.LOGIN_CODE_KEY + phone, 60 * 5);
        return Result.ok();
    }

    @Override
    public Result verifyCode(String phone, String code) {
        String oldCode = Db.jedis.get(RedisConstant.LOGIN_CODE_KEY + phone);
        if (oldCode == null){
            return Result.fail("验证码不存在或者已过期");
        }
        if (!oldCode.equals(code)){
            return Result.fail("验证码错误");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("phone",phone);
        String token = JwtUtils.createJwtToken(map);
        return Result.ok(token);
    }

    @Override
    public Result register(String phone) {
        try {
            System.out.println(phone);
            String code = SendMessageUtil.sendMessage(phone);
            if (code == null) {
                return Result.fail("服务器内部错误,发送短信失败");
            }
            Db.jedis.set(RedisConstant.LOGIN_CODE_KEY + phone, code);
            Db.jedis.expire(RedisConstant.LOGIN_CODE_KEY + phone, 60 * 5);
        } catch (Exception e) {
            return  Result.fail("服务器内部错误,发送短信失败");
        }
        return Result.ok();
    }
    @Override
    public Result registerSave(String phone) {
        User user = userMapper.selectByPhone(phone);
        if (user != null){
            return Result.fail("该用户已存在");
        }
        User newUser = new User();
        newUser.setPhone(phone);
        int rows = userMapper.insert(newUser);
        HashMap<String, Object> map = new HashMap<>();
        map.put("phone",phone);
        String token = JwtUtils.createJwtToken(map);
        return rows == 1 ? Result.ok(token) : Result.fail("失败");
    }

    @Override
    public Result shiming(User user) {
        User oldUser = userMapper.selectByPhone(user.getPhone());
        if (oldUser == null){
            return Result.fail("该用户不存在");
        }
        User user1 = userMapper.selectByIdCard(user.getIdcard());
        if (user1 != null){
            return Result.fail("该实名已被其它人认证");
        }
        ShiMingCheckEnum check = IdCardCheckUtil.check(user.getName(), user.getIdcard());
        if (check == ShiMingCheckEnum.ERROR){
            return Result.fail("修改实名失败");
        }
        if (check == ShiMingCheckEnum.NOT_EXIST){
            return Result.fail("身份证信息不存在,请输入正确的身份证");
        }
        if (check == ShiMingCheckEnum.INCONSISTENT){
            return Result.fail("名字和身份证不匹配,请正确输入");
        }
        user.setId(oldUser.getId());
        int rows = userMapper.updateByPrimaryKeySelective(user);
        return rows == 1 ? Result.ok() : Result.fail("修改实名失败");
    }

    @Override
    public Result getPatients(String phone) {
        User user = userMapper.selectByPhoneWithPatients(phone);
        List<Patient> patients = user.getPatients();
        if (patients == null){
            return Result.fail("未找到对应的就诊人");
        }
        for (Patient patient : patients) {
            String name = patient.getName();
            String xing = "";
            for (int i = 0; i < name.length() - 1; i++) {
                xing += "*";
            }
            patient.setName(xing + name.substring(name.length() - 1));
            String idcard = patient.getIdcard();
            patient.setIdcard(idcard.substring(0,3) + "****" + idcard.substring(idcard.length() - 2));
        }
        return Result.ok(patients);
    }

    @Override
    public Result selUserByPhone(String phone) {
        User user = userMapper.selectByPhone(phone);
        if (user == null){
            return Result.fail("失败");
        }
        String name = user.getName();
        String xing = "";
        for (int i = 0; i < name.length() - 1; i++) {
            xing += "*";
        }
        user.setName(xing + name.substring(name.length() - 1));
        String idcard = user.getIdcard();
        user.setIdcard(idcard.substring(0,3) + "****" + idcard.substring(idcard.length() - 2));
        return Result.ok(user);
    }



    public Result SelNameAndIdCardById(Integer id) {
        User user = userMapper.SelNameAndIdCardById(id);
        if (user == null) {
            return Result.fail("失败");
        }
        String name = user.getName();
        String xing = "";
        for (int i = 0; i < name.length() - 1; i++) {
            xing += "*";
        }
        user.setName(xing + name.substring(name.length() - 1));
        String idcard = user.getIdcard();
        user.setIdcard(idcard.substring(0, 3) + "****" + idcard.substring(idcard.length() - 2));
        return Result.ok(user);
    }

    @Override
    public Result findUserByPhone(String phone) {
       Integer userId=  userMapper.findUserByPhoen(phone);
        return userId!=null?Result.ok(userId):Result.fail();
    }

    public Result findAllPatients(String phone,String input) {
        User user = userMapper.selectByPhoneWithPatients(phone);
        List<Patient> patients = user.getPatients();
        if (patients == null) {
            return Result.fail("未找到对应的就诊人");
        }
        for (Patient patient : patients) {
            String idCard = patient.getIdcard();
            String actualLastSix = idCard.substring(idCard.length() - 6);
            if (actualLastSix.equals(input)) {
                return Result.ok();
            } else {
                return Result.fail();
            }
        }
        return Result.fail();
    }

    @Override
    public Result SelphoneById(Integer id) {
        User user = userMapper.SelphoneById(id);
        return Result.ok(user);
    }

    @Override
    public Result UpdatephoneById(Integer id, String phone) {
        int rows = userMapper.UpdatephoneById(id, phone);
        return rows == 1 ? Result.ok() : Result.fail("修改失败");

    }

    @Override
    public Result updateSendMsg(String phone) {
        String code = null;
        try {
            code = SendMessageUtil.sendMessage(phone);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("服务器内部错误,发送短信失败");
        }
        if (code == null) {
            return Result.fail("服务器内部错误,发送短信失败");
        }
        Db.jedis.set(RedisConstant.UPDATE_CODE_KEY + phone, code);
        Db.jedis.expire(RedisConstant.UPDATE_CODE_KEY + phone, 60 * 5);
        return Result.ok();
    }

    @Override
    public Result updatePhone(String oldPhone,String newPhone, String code) {
        String oldCode = Db.jedis.get(RedisConstant.UPDATE_CODE_KEY + newPhone);
        if (oldCode == null){
            return Result.fail("验证码不存在或者已过期");
        }
        if (!oldCode.equals(code)){
            return Result.fail("验证码错误");
        }
        User user = userMapper.selectByPhone(newPhone);
        if (user != null){
            return Result.fail("该手机号已绑定其它用户");
        }
        User oldUser = userMapper.selectByPhone(oldPhone);
        if (oldUser == null){
            return Result.fail("用户不存在");
        }
        oldUser.setPhone(newPhone);
        int rows = userMapper.updateByPrimaryKey(oldUser);
        return rows == 1 ? Result.ok() : Result.fail("修改失败");
    }
}
